package com.golddaymicromall.wxapi;

import com.golddaymicromall.activity.R;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.golddaymicromall.activity.Constants;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXPayEntryActivity";

    private IWXAPI api;
    private TextView mPayStatus;
    String flag;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_result);

        mPayStatus = (TextView) findViewById(R.id.paystatus);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);
        switch (resp.errCode) {
            case 0://支付成功后的界面
                attemptNotifyServer();
                break;
            case -1:
                Toast.makeText(this, "签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、您的微信账号异常等。", Toast.LENGTH_SHORT).show();
                break;
            case -2://用户取消支付后的界面
                mPayStatus.setText("您已取消订单，请返回。");
                break;
        }
    }

    private void attemptNotifyServer() {
        String orderId = SPUtils.get(getApplicationContext(), "orderId", "").toString();
        String addressId = SPUtils.get(getApplicationContext(), "addressid", "").toString();
        SPUtils.remove(getApplicationContext(),"orderId");
        SPUtils.remove(getApplicationContext(),"addressid");

        notifyServerTask(orderId,"2",addressId);
    }
    //通知服务端改为待发货
    public void notifyServerTask(String id, String orderStatus, String addressId){
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.dporder.zhangpay");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("ids", id);
        form.put("orderStatus", orderStatus);
        form.put("addressid", addressId);
        form.put("paytype", "微信支付");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(WXPayEntryActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(WXPayEntryActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else if ("1".equals(result)) {
                            mPayStatus.setText("付款成功,请静待发货");
                        } else {
                            mPayStatus.setText("取消订单失败,请重新进入该页面进行删除操作");
                        }
                    } else {
                        Toast.makeText(WXPayEntryActivity.this, "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                    throwable.printStackTrace();
                });
    }
}